Grokking Microsoft Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Microsoft Easy Problems
Buddy Strings (easy)
Solution: Buddy Strings
Can Place Flowers (easy)
Solution: Can Place Flowers
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Maximum Number of Balloons (easy)
Solution: Maximum Number of Balloons
Binary Tree Path Sum (easy)
Solution: Binary Tree Path Sum
Pair with Target Sum (easy)
Solution: Pair with Target Sum
Buy Two Chocolates (easy)
Solution: Buy Two Chocolates
Root Equals Sum of Children (easy)
Solution: Root Equals Sum of Children
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Min Cost Climbing Stairs (easy)
Solution: Min Cost Climbing Stairs
Plus One (easy)
Solution: Plus One
Intersection of Two Arrays (easy)
Solution: Intersection of Two Arrays
Find the Index of the First Occurrence in a String (easy)
Solution: Find the Index of the First Occurrence in a String
Merge Two Sorted Lists (easy)
Solution: Merge Two Sorted Lists
Nth Digit (medium)
Solution: Nth Digit
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Find Original Array From Doubled Array (medium)
Solution: Find Original Array From Doubled Array
Reverse Words in a String II (medium)
Solution: Reverse Words in a String II
Longest Arithmetic Subsequence (medium)
Solution: Longest Arithmetic Subsequence
Matchsticks to Square (medium)
Solution: Matchsticks to Square
Score of Parentheses (medium)
Solution: Score of Parentheses
Maximum Length of a Concatenated String with Unique Characters (medium)
Solution: Maximum Length of a Concatenated String with Unique Characters
Inorder Successor in BST (medium)
Solution: Inorder Successor in BST
Distribute Coins in Binary Tree (medium)
Solution: Distribute Coins in Binary Tree
Spiral Matrix (medium)
Solution: Spiral Matrix
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Rotate Image (medium)
Solution: Rotate Image
Combinations (medium)
Solution: Combinations
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Multiply Strings (medium)
Solution: Multiply Strings
Best Time to Buy and Sell Stock II (medium)
Solution: Best Time to Buy and Sell Stock II
Largest Palindromic Number (medium)
Solution: Largest Palindromic Number
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Next Permutation (medium)
Solution: Next Permutation
132 Pattern (medium)
Solution: 132 Pattern
Valid Sudoku (medium)
Solution: Valid Sudoku
Number of Islands (medium)
Solution: Number of Islands
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Regular Expression Matching (hard)
Solution: Regular Expression Matching
First Missing Positive (hard)
Solution: First Missing Positive
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Sliding Window Maximum (hard)
Solution: Sliding Window Maximum
Count Unique Characters of All Substrings of a Given String (hard)
Solution: Count Unique Characters of All Substrings of a Given String
Word Ladder (hard)
Solution: Word Ladder
Word Ladder II (hard)
Solution: Word Ladder II
Number of Flowers in Full Bloom (hard)
Solution: Number of Flowers in Full Bloom
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Solution: Binary Tree Path Sum

Problem Statement

Given a root of the binary tree and an integer S, return true if the tree has a path from root-to-leaf such that the sum of all the node values of that path equals S. Otherwise, return false.

Examples

Example 1:

  • Input: root = [1, 2, 3, 4, 5, 6, 7], S = 10
Image
  • Expected Output: true
  • Justification: The tree has 1 -> 3 -> 6 root-to-leaf path having sum equal to 10.

Example 2:

  • Input: root = [12, 7, 1, 9, null, 10, 5], S = 23
Image
  • Expected Output: true
  • Justification: The tree has 12 -> 1 -> 10 root-to-leaf path having sum equal to 23.

Example 3:

  • Input: root = [12, 7, 1, 9, null, 10, 5], S = 16
Image
  • Expected Output: false
  • Justification: The tree doesn't have root-to-leaf path having sum equal to 16.

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

Solution

The Binary Tree Path Sum problem involves determining whether there is a root-to-leaf path in a binary tree such that the sum of the node values along the path equals a given target sum. The algorithm traverses the tree recursively, adjusting the target sum at each step by subtracting the value of the current node. At each step, we pass the updated target sum to the recursive DFS call. If a leaf node is reached and its value matches the adjusted sum, a valid path has been found.

Step-by-Step Algorithm

  1. Check if the root is null:

    • If the root is null, return false because there is no path in an empty tree.
  2. Check if the current node is a leaf:

    • If the current node is a leaf, and its value matches the current sum (target sum minus the values encountered so far), return true, indicating that a valid path has been found.
  3. Traverse the left and right subtrees:

    • If the current node is not a leaf, adjust the sum by subtracting the value of the current node from the target sum.
    • Recursively check both the left and right children, passing the updated sum to both recursive calls.
  4. Return true if any recursive call returns true:

    • If any of the recursive calls (left or right subtree) returns true, return true to indicate that a valid path has been found.
    • Otherwise, return false if neither of the recursive calls finds a valid path.

Algorithm Walkthrough

Image
  1. Step 1 - Start at the root node (12):

    • The current node is 12.
    • The target sum is 23.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: No (it has left and right children).
    • Subtract the current node's value from the target sum: 23 - 12 = 11.
    • Now recursively check both the left and right subtrees, with the new sum 11.
  2. Step 2 - Traverse the left subtree (Node 7):

    • The current node is 7.
    • The target sum is 11.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: No (it has a left child).
    • Subtract the current node's value from the target sum: 11 - 7 = 4.
    • Now recursively check the left subtree with the new sum 4 (as the right child is null).
  3. Step 3 - Traverse the left subtree (Node 9):

    • The current node is 9.
    • The target sum is 4.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: Yes (it has no left or right children).
    • Check if the current node's value matches the target sum: 9 != 4.
    • Since the values do not match, return false and backtrack to node 7.
  4. Step 4 - Traverse the right subtree of Node 12 (Node 1):

    • Backtrack to node 12 and now traverse its right subtree.
    • The current node is 1.
    • The target sum is 11 (from step 1).
    • Check if the current node is null: No.
    • Check if the current node is a leaf: No (it has left and right children).
    • Subtract the current node's value from the target sum: 11 - 1 = 10.
    • Now recursively check both the left and right subtrees with the new sum 10.
  5. Step 5 - Traverse the left subtree (Node 10):

    • The current node is 10.
    • The target sum is 10.
    • Check if the current node is null: No.
    • Check if the current node is a leaf: Yes (it has no left or right children).
    • Check if the current node's value matches the target sum: 10 == 10.
    • Since the values match, return true indicating that a valid path (12 → 1 → 10) has been found.
  6. Step 6 - Return final result:

    • Since we found a valid path in step 5, the algorithm returns true for the input tree and sum 23.

Final Output:

  • The tree has a path with a sum of 23: 12 → 1 → 10. Hence, the result is true.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the above algorithm is , where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be in the worst case. This space will be used to store the recursion stack. The worst case will happen when the given tree is a linked list (i.e., every node has only one child).

Binary Tree Path Sum (easy)
Pair with Target Sum (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Final Output:

Code

Complexity Analysis

Time Complexity

Space Complexity